package com.jz.netthings.analysis.service.impl;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jz.netthings.analysis.bean.ProviderRound;
import com.jz.netthings.analysis.bean.ProviderRoundBase;
import com.jz.netthings.analysis.bean.ProviderType;
import com.jz.netthings.analysis.mapper.ProviderInfoDzjwdMapper;
import com.jz.netthings.analysis.mapper.ProviderRoundBase2Mapper;
import com.jz.netthings.analysis.mapper.ProviderRoundBaseMapper;
import com.jz.netthings.analysis.mapper.ProviderRoundMapper;
import com.jz.netthings.analysis.service.ProviderInfoDzjwdService;
import com.jz.netthings.analysis.service.ProviderRoundBaseService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jz.netthings.appengine.baseData.ProviderInfo;
import com.jz.netthings.appengine.mapper.ProviderInfoMapper;
import com.jz.netthings.bloodsources.bean.XyLink;
import com.jz.netthings.bloodsources.mapper.XyLinkMapper;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.support.AdscmPage;
import com.jz.netthings.utils.AdscmBaseUtils;
import com.jz.netthings.utils.AdscmDateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 供浆者轮次表的基础统计数据 服务实现类
 * </p>
 *
 * @author yangyunyun
 * @since 2019-07-16
 */
@Service
public class ProviderRoundBaseServiceImpl extends ServiceImpl<ProviderRoundBaseMapper, ProviderRoundBase> implements ProviderRoundBaseService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    ProviderRoundBaseMapper providerRoundBaseMapper;
    @Autowired
    ProviderInfoMapper providerInfoMapper;
    @Autowired
    ProviderRoundMapper providerRoundMapper;
    @Autowired
    ProviderInfoDzjwdService providerInfoDzjwdService;
    @Autowired
    ProviderInfoDzjwdMapper providerInfoDzjwdMapper;
    @Autowired
    XyLinkMapper xyLinkMapper;


    @Override
    public ProviderRoundBase loadRoundBase(Long providerId) throws AdscmSystemException {

        logger.info("开始构造供浆者【"+providerId+"】的轮次基础统计数据...");
        ProviderRoundBase base = null;

        if (providerId != null && providerId > 0){
            base = providerRoundBaseMapper.selectById(providerId);
            boolean isInsert = false;
            if (base == null){
                isInsert = true;
                base = new ProviderRoundBase();
            }
            ProviderInfo info = providerInfoMapper.selectById(providerId);
            if(info != null){
                base.setId(info.getId());
                //浆龄
                int between = AdscmDateUtils.daysBetween(info.getCreateDate(), new Date());
                base.setPulpAge(between/365);

                Date now = new Date();
                String nowStr = AdscmDateUtils.getNowOnlyDateFomat1(now);
                int nowYear = AdscmDateUtils.getTheYear(now);

                //今年当期总次数
                String beginTime = nowYear + "-01-01 00:00:00";
                String endTime = nowStr + " 23:59:59";
                int currentYearAllCollNum = providerRoundBaseMapper.selectProviderCollNum(providerId,beginTime,endTime);
                base.setCurrentYearAllCollNum(currentYearAllCollNum);

                //去年同期总次数
                beginTime = (nowYear-1) + "-01-01 00:00:00";
                String lastTimeStr =AdscmDateUtils.getNowOnlyDateFomat1(now,-1);
                endTime = lastTimeStr + " 23:59:59";
                int lastYearCurrentTimeCollNum = providerRoundBaseMapper.selectProviderCollNum(providerId,beginTime,endTime);
                base.setLastYearCurrentTimeCollNum(lastYearCurrentTimeCollNum);

                //去年献浆总次数
                endTime = (nowYear-1) + "-12-31 23:59:59";
                int lastYearAllCollNum = providerRoundBaseMapper.selectProviderCollNum(providerId,beginTime,endTime);
                base.setLastYearAllCollNum(lastYearAllCollNum);

                //献浆总次数
                beginTime = AdscmDateUtils.getNowOnlyDateFomat1(info.getCreateDate()) + " 00:00:00";
                endTime = nowStr + " 23:59:59";
                int allCollNum = providerRoundBaseMapper.selectProviderCollNum(providerId,beginTime,endTime);
                base.setAllCollNum(allCollNum);

                if (isInsert){
                    providerRoundBaseMapper.insert(base);
                }else {
                    providerRoundBaseMapper.updateById(base);
                }
            }else {
                logger.warn("构造失败，没有找到供浆者信息");
            }
        }else {
            logger.warn("构造失败，参数 供浆者ID 为null");
        }
        return base;
    }

    @Override
    public void loadAllProviderRoundBase() throws AdscmSystemException {
        logger.info("开始构造供所有浆员的轮次基础统计数据...");
        List<ProviderInfo> list = providerInfoMapper.selectList(null);
        for (ProviderInfo info : list) {
            try{
                this.loadRoundBase(info.getId());
            }catch (Exception e){
                logger.error("构造供浆者【"+info.getId()+"】的轮次基础统计数据异常",e);
            }
        }
    }


    @Override
    public List<ProviderRoundBase> getRegProviderRound(String villageName, String date, boolean isNew, boolean isPositive) throws AdscmSystemException {

        logger.info("查询村落【"+villageName+"】【"+date+"】登记的浆员的轮次信息...");

        List<ProviderRoundBase> providerRoundBases = null;
        String beginTime = date + " 00:00:00";
        String endTime = date + " 23:59:59";
        if (!isNew){
            if (isPositive){
                //当天的积极浆员（在第一个登记到第一个体检这段时间内的）
                endTime = providerInfoDzjwdService.getMinBodyCheckEndTime(date);
            }
        }
        providerRoundBases = providerRoundBaseMapper.selectRoundBaseByRegDate(villageName, beginTime, endTime, (isNew ? "1" : "0"));

        if (providerRoundBases != null && providerRoundBases.size()>0){
            for (ProviderRoundBase providerRoundBase : providerRoundBases) {
                this.loadProviderRoundBase(providerRoundBase);
            }
        }

        return providerRoundBases;
    }

    /**
     * 获取护士、义工
     * @param providerRoundBase
     */
    @Override
    public void getNurseYg(ProviderRoundBase providerRoundBase) {
        Wrapper<XyLink> wrapper = new EntityWrapper<>();
        wrapper.eq("linkProviderId",providerRoundBase.getId());
        List<XyLink> xyLinks = xyLinkMapper.selectList(wrapper);
        if (AdscmBaseUtils.getInstance().listIsNotEmpty(xyLinks)){
            XyLink link = xyLinks.get(0);
            if (link != null){
                try{
                    //管理护士
                    providerRoundBase.setConnNurseId(link.getUseNurseId().intValue());
                    providerRoundBase.setConnNurseName(link.getUseNurseName());

                    //管理义工
                    providerRoundBase.setYiGongId(link.getUseVolunteeId().toString());
                    providerRoundBase.setYiGongName(link.getUseVolunteeName());

                }catch (Exception e){
                    logger.error(e.getMessage());
                }
            }
        }
    }

    private void loadProviderRoundBase(ProviderRoundBase providerRoundBase){
        //查询重点浆员类型名称

        //性别
        if(providerRoundBase.getGender().equals("1")){
            providerRoundBase.setGender("男");
        }else {
            providerRoundBase.setGender("女");
        }

        //管理护士
        //管理义工
        this.getNurseYg(providerRoundBase);

        //当前年的轮次记录
        int currentYear = AdscmDateUtils.getTheYear(new Date());
        ProviderRound round = new ProviderRound(false);
        round.setYear(currentYear);
        round.setProviderId(providerRoundBase.getId());
        ProviderRound currentYearRound = providerRoundMapper.selectOne(round);
        if(currentYearRound == null){
            currentYearRound = new ProviderRound(true);
        }
        providerRoundBase.setCurrentYearRound(currentYearRound);

        //上一年的轮次记录
        int lastYear = currentYear - 1;
        round.setYear(lastYear);
        ProviderRound lastYearRound = providerRoundMapper.selectOne(round);
        if(lastYearRound == null){
            lastYearRound = new ProviderRound(true);
        }
        providerRoundBase.setLastYearRound(lastYearRound);

        List<ProviderRound> allRound = new ArrayList<>();
        allRound.add(0,lastYearRound);
        allRound.add(1,currentYearRound);

        providerRoundBase.setAllRound(allRound);

    }

    @Autowired
    ProviderRoundBase2Mapper providerRoundBase2Mapper;

    @Override
    public AdscmPage<ProviderRoundBase> getProviderRound(String villageName, String providerType, int current, int size) throws AdscmSystemException {

        ProviderType type = ProviderType.getByValue(providerType);
        logger.info("分页查询村落【"+villageName+"】【"+type.getDesc()+"】类型的浆员的轮次信息");

        current = AdscmBaseUtils.getInstance().getCurrentStartIdx(current,size);

        AdscmPage<ProviderRoundBase> page = new AdscmPage<>(current,size);
        Map<String,Object> condition = new HashMap<>();

        List<ProviderRoundBase> list = null;
        int count = 0;
        condition.put("villageName",villageName);

        Date now = new Date();
        String nowStr = AdscmDateUtils.getNowOnlyDateFomat1(now);
        int nowYear = AdscmDateUtils.getTheYear(now);

        int currentYear = AdscmDateUtils.getTheYear(now);
        int lastYear = currentYear - 1;

        if (type == ProviderType.ALL_PROVIDER){
            page.setCondition(condition);
//            list = providerRoundBaseMapper.selectVillAllProviderRoundByPage(page);
            list = providerRoundBase2Mapper.selectVillAllProviderRound(villageName,currentYear,lastYear);
            count = providerRoundBaseMapper.selectVillAllProviderRoundCount(condition);
        }else if (type == ProviderType.THIS_YEAR_COMED){
            //今年已进站浆员
            condition.put("beginTime", nowYear + "-01-01 00:00:00");
            condition.put("endTime", nowStr + " 23:59:59");
            page.setCondition(condition);
//            list = providerRoundBaseMapper.selectVillThisYearComedRoundByPage(page);
            list = providerRoundBase2Mapper.selectVillThisYearComedRound(currentYear,lastYear,page);
            count = providerRoundBaseMapper.selectVillThisYearComedRoundCount(page);
        }else if (type == ProviderType.ZC_PROVIDER){
            //忠诚浆员
            this.setConditionTime(condition,nowStr,nowYear);

            page.setCondition(condition);
//            list = providerRoundBaseMapper.selectVillZcProviderRoundByPage(page);
            list = providerRoundBase2Mapper.selectVillZcProviderRound(currentYear,lastYear,page);
            count = providerRoundBaseMapper.selectVillZcProviderRoundCount(page);
        }else if (type == ProviderType.FS_PROVIDER){
            //复苏浆员
            this.setConditionTime(condition,nowStr,nowYear);
            page.setCondition(condition);
//            list = providerRoundBaseMapper.selectVillFusuProviderRoundByPage(page);
            list = providerRoundBase2Mapper.selectVillFusuProviderRound(currentYear,lastYear,page);
            int currentTimeFuSuPNum = providerInfoDzjwdMapper.selectCurrentTimeFuSuPNum(villageName,condition.get("beginTime1").toString(),condition.get("endTime1").toString(),condition.get("beginTime2").toString(),condition.get("endTime2").toString());//当期复苏献浆员总人数
            count = currentTimeFuSuPNum;//providerRoundBaseMapper.selectVillFusuProviderRoundCount(page);
        }else if (type == ProviderType.NEW_PROVIDER){
            //今年新浆员
            condition.put("beginTime", nowYear + "-01-01 00:00:00");
            condition.put("endTime", nowStr + " 23:59:59");
            page.setCondition(condition);
//            list = providerRoundBaseMapper.selectVillNewProviderRoundByPage(page);
            list = providerRoundBase2Mapper.selectVillNewProviderRound(currentYear,lastYear,page);
            int currentTimeAddPNum = providerInfoDzjwdMapper.selectCurrentTimeAddPNum(villageName,nowYear + "-01-01 00:00:00",nowStr + " 23:59:59");
            count = currentTimeAddPNum;//providerRoundBaseMapper.selectVillFusuProviderRoundCount(page);
        }else if(type == ProviderType.NOT_LINK_PROVIDER){
            //未被链接浆员
            count = 0;
            list = new ArrayList<>();
        }else if(type == ProviderType.THIS_YEAR_NOT_COMED){
            //今年未进站
            condition.put("beginTime", nowYear + "-01-01 00:00:00");
            condition.put("endTime", nowStr + " 23:59:59");
            page.setCondition(condition);
//            list = providerRoundBaseMapper.selectVillCurrentTimeNotComedRoundByPage(page);
            list = providerRoundBase2Mapper.selectVillCurrentTimeNotComedRound(currentYear,lastYear,page);
            int currentTimeNotComedPNum = providerInfoDzjwdMapper.selectCurrentTimeNotComedPNum(villageName,nowYear + "-01-01 00:00:00",nowStr + " 23:59:59");//当期未进站总人数
            count = currentTimeNotComedPNum;
        }else if(type == ProviderType.XM_PROVIDER){
            //休眠浆员
            String beginTime1 = (nowYear - 1) + "-01-01 00:00:00";//开始时间1：去年的开始
            String endTime1 = (nowYear - 1) + "-12-31 23:59:59";//开始时间1：去年的结束

            String beginTime2 = nowYear + "-01-01 00:00:00";//开始时间2：今年的开始
            String endTime2 = nowStr + " 23:59:59";//开始时间2：今年的当前时间

            this.setConditionTime(condition,nowStr,nowYear);
            page.setCondition(condition);
//            list = providerRoundBaseMapper.selectVillXiuMianRoundByPage(page);
            list = providerRoundBase2Mapper.selectVillXiuMianRound(currentYear,lastYear,page);
            int xiuMianPNum = providerInfoDzjwdMapper.selectXiuMianPNum(villageName,beginTime1,endTime1,beginTime2,endTime2);
            count = xiuMianPNum;
        }else if(type == ProviderType.LINKED_XM_PROVIDER){
            //已链接的休眠浆员
            count = 0;
            list = new ArrayList<>();
        }else if(type == ProviderType.NOT_LINKED_XM_PROVIDER){
            //已链接的休眠浆员
            count = 0;
            list = new ArrayList<>();
        }else if(type == ProviderType.LS_PROVIDER){
            //流失浆员
            condition.put("beginTime", (nowYear - 1) + "-01-01 00:00:00");
            condition.put("endTime", nowStr + " 23:59:59");

            page.setCondition(condition);
//            list = providerRoundBaseMapper.selectVillCurrentTimeNotComedRoundByPage(page);
            list = providerRoundBase2Mapper.selectVillCurrentTimeNotComedRound(currentYear,lastYear,page);
            int liuShiPNum = providerInfoDzjwdMapper.selectCurrentTimeNotComedPNum(villageName,condition.get("beginTime").toString(),condition.get("endTime").toString());
            count = liuShiPNum;
        }

        //添加管理护士、义工、最新沟通内容
        if (AdscmBaseUtils.getInstance().listIsNotEmpty(list)){
            for (ProviderRoundBase providerRoundBase : list) {
//                this.loadProviderRoundBase(providerRoundBase);
                //管理护士
                //管理义工
                this.getNurseYg(providerRoundBase);
            }
        }
        page.setRecords(list);
        page.setTotal(count);

        return page;
    }

    private void setConditionTime(Map<String,Object> condition,String nowStr,int nowYear){
        condition.put("beginTime1", (nowYear - 1) + "-01-01 00:00:00");
        condition.put("endTime1", (nowYear - 1) + "-12-31 23:59:59");

        condition.put("beginTime2", nowYear + "-01-01 00:00:00");
        condition.put("endTime2", nowStr + " 23:59:59");
    }


}
